import React, { useState } from "react";
import { Modal, Form, Input, Button, message, Steps } from "antd";
import EmailVerifyModal from "@/components/EmailVerifyModal";
import { resetPassword } from "@/api/xhr/user/index";

interface ForgotPasswordModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: (userAccount: string, password: string) => void;
}

const ForgotPasswordModal: React.FC<ForgotPasswordModalProps> = ({
  open,
  onCancel,
  onSuccess
}) => {
  const [form] = Form.useForm();
  const [email, setEmail] = useState("");
  const [currentStep, setCurrentStep] = useState(0);
  const [verifyModalVisible, setVerifyModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  
  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentStep === 0) {
        // 第一步：提交邮箱，打开验证码模态框
        setEmail(values.email);
        setVerifyModalVisible(true);
      } else {
        // 第二步：提交新密码
        setLoading(true);
        const { password, confirmPassword } = values;
        
        if (password !== confirmPassword) {
          message.error("两次输入的密码不一致");
          return;
        }
        
        try {
          const res = await resetPassword(email, password);
          if (res.statusCode === 200) {
            message.success("密码重置成功，正在自动填充登录信息...");
            form.resetFields();
            setCurrentStep(0);
            // 传递账号和密码给父组件，用于自动填充登录表单
            onSuccess(res.data.userAccount, res.data.password);
          } else {
            message.error(res.errorInfo || "密码重置失败");
          }
        } catch (error) {
          console.error("重置密码出错:", error);
          message.error("密码重置失败，请稍后重试");
        } finally {
          setLoading(false);
        }
      }
    } catch (error) {
      console.error("表单验证失败:", error);
    }
  };
  
  // 邮箱验证成功
  const handleVerifySuccess = () => {
    setVerifyModalVisible(false);
    setCurrentStep(1);
  };
  
  // 取消验证
  const handleVerifyCancel = () => {
    setVerifyModalVisible(false);
  };
  
  // 重置表单和状态
  const handleCancel = () => {
    form.resetFields();
    setCurrentStep(0);
    onCancel();
  };
  
  return (
    <>
      <Modal
        title="找回密码"
        open={open}
        onCancel={handleCancel}
        footer={[
          <Button key="cancel" onClick={handleCancel}>
            取消
          </Button>,
          <Button 
            key="submit" 
            type="primary" 
            onClick={handleSubmit}
            loading={loading}
          >
            {currentStep === 0 ? "下一步" : "重置密码"}
          </Button>
        ]}
      >
        <div className="py-4">
          <Steps
            current={currentStep}
            items={[
              { title: "验证邮箱" },
              { title: "重置密码" }
            ]}
            className="mb-6"
          />
          
          <Form 
            form={form} 
            layout="vertical"
          >
            {currentStep === 0 ? (
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: "请输入邮箱" },
                  { type: "email", message: "请输入正确的邮箱地址" }
                ]}
              >
                <Input placeholder="请输入您账号绑定的邮箱" />
              </Form.Item>
            ) : (
              <>
                <p className="mb-4">邮箱验证成功，请设置新密码</p>
                <Form.Item
                  name="password"
                  label="新密码"
                  rules={[
                    { required: true, message: "请输入新密码" },
                    { min: 6, message: "密码至少6位" },
                    { max: 20, message: "密码最长20位" }
                  ]}
                >
                  <Input.Password placeholder="请输入新密码" />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  label="确认密码"
                  rules={[
                    { required: true, message: "请确认密码" },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue("password") === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error("两次输入的密码不一致"));
                      }
                    })
                  ]}
                >
                  <Input.Password placeholder="请再次输入新密码" />
                </Form.Item>
              </>
            )}
          </Form>
        </div>
      </Modal>
      
      <EmailVerifyModal
        open={verifyModalVisible}
        email={email}
        onCancel={handleVerifyCancel}
        onSuccess={handleVerifySuccess}
        type="update"
      />
    </>
  );
};

export default ForgotPasswordModal; 